package com.py.credit.service.impl;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.dao.IndexDao;
import com.py.credit.entity.ColumnAndCal;
import com.py.credit.entity.FinanceModel;
import com.py.credit.entity.Index;
import com.py.credit.service.IndexService;
import com.py.credit.utils.SQLBuilder;
import com.py.credit.utils.UuidUtil;
import com.py.framework.core.common.Page;

@Service
public class IndexServiceImpl implements IndexService {

	@Autowired
	private IndexDao indexDao;

	@Override
	public void insertIndex(Index index) {
		index.setId(UuidUtil.getUUid());
		indexDao.insertIndex(index);

	}

	@Override
	public Index selectIndexById(String id, String name, String type, String mainType) {
		Map<String, String> params = new HashMap<>();
		params.put("id", id);
		params.put("name", name);
		params.put("type", type);
		params.put("mainType", mainType);

		return indexDao.selectIndexById(params);
	}

	@Override
	public void updateIndexById(Index index) {
		indexDao.updateIndexById(index);

	}

	@Override
	public void deleteIndexById(List<String> id) {
		indexDao.deleteIndexById(id);

	}

	@Override
	public List<Index> getIndexForPage(String type, String mainType, String name, Page page) {
		Map<String, String> indexMap = new HashMap<>();
		indexMap.put("type", type);
		indexMap.put("mainType", mainType);
		indexMap.put("name", name);
		return indexDao.getIndexForPage(indexMap, page);
	}

	@Override
	public Integer indexDelCheck(List<String> list) {
		return indexDao.indexDelCheck(list);
	}

	@Override
	public List<Integer> selectRelateSourceById(List<String> list) {
		List<String> datas = indexDao.selectRelateSourceById(list);
		List<Integer> source = new ArrayList<>();
		if (datas.size() > 0) {
			for (int i = 0; i < datas.size(); i++) {

				String[] sources1 = datas.get(i).split(",");

				List<String> sources2 = Arrays.asList(sources1);

				for (int j = 0; j < sources2.size(); ++j) {

					if (!source.contains(sources2.get(j))) {
						source.add(Integer.parseInt(sources2.get(j)));
					}

				}
			}
		}

		return source;
	}

	@Override
	public List<LinkedHashMap> selectTreeFromIndex(String mainType, String name) {

		return indexDao.selectTreeFromIndex(mainType, name);
	}

	@Override
	public List<LinkedHashMap<String, Object>> getByConditionForPage(String type, String mainType, String name,
			String status, List<String> columns, String[] additionalColumns, String conditionStr, Page page) {
		List<String> conditions = SQLBuilder.createConditionSql(conditionStr);
		Map<String, String> indexMap = new HashMap<>();
		indexMap.put("type", type);
		indexMap.put("mainType", mainType);
		indexMap.put("name", name);
		indexMap.put("status", status);
		List<LinkedHashMap<String, Object>> batchLogs = indexDao.selectByConditionForPage(indexMap, columns,
				additionalColumns, conditions, page);

		return batchLogs;
	}

	@Override
	public List<Map<String, Object>> searchFinance(String pdId) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("pgId", pdId);
		return indexDao.searchFinance(map);
	}

	@Override
	public void saveFinanceData(String pgId) {
		// 查询所有财务信息
		List<Map<String, Object>> fallMaps = indexDao.searchAllData(pgId);
		indexDao.deleteFinanceData(pgId);
		@SuppressWarnings("unused")
		int j = fallMaps.size();
		for (int i = 0; i < j; i++) {
			if (i >= 1 && i <= j) {
				// 货币资金6
				String monetaryFund = fallMaps.get(i).get("MONETARY_FUND").toString();
				// 货币资金6---上一年度
				String monetaryFundLast = fallMaps.get(i - 1).get("MONETARY_FUND").toString();
				// 应收账款9
				String accountsReceivable = fallMaps.get(i).get("ACCOUNTS_RECEIVABLE").toString();
				// 应收账款9----上一年度
				String accountsReceivableLast = fallMaps.get(i - 1).get("ACCOUNTS_RECEIVABLE").toString();
				// 存货14
				String stock = fallMaps.get(i).get("STOCK").toString();
				// 存货14----上一年度
				String stockLast = fallMaps.get(i - 1).get("STOCK").toString();
				// 流动资产合计17
				String totalCurrentAssets = fallMaps.get(i).get("TOTAL_CURRENT_ASSETS").toString();
				// 流动资产合计17----上一年度
				String totalCurrentAssetsLast = fallMaps.get(i - 1).get("TOTAL_CURRENT_ASSETS").toString();
				// 资产总计39
				String totalAssets = fallMaps.get(i).get("TOTAL_ASSETS").toString();
				// 资产总计39---上一年度的
				String totalAssetsLast = fallMaps.get(i - 1).get("TOTAL_ASSETS").toString();
				// 短期借款42
				String shorttermLoan = fallMaps.get(i).get("SHORTTERM_LOAN").toString();
				// 应付账款45
				String accountsPayable = fallMaps.get(i).get("ACCOUNTS_PAYABLE").toString();
				// 应付利息49
				String interestPayable = fallMaps.get(i).get("INTEREST_PAYABLE").toString();
				// 一年内到期的非流动负债52
				String duenonCurrentLiabilities = fallMaps.get(i).get("DUENON_CURRENT_LIABILITIES").toString();
				// 流动负债合计54
				String totalCurrentLiabilities = fallMaps.get(i).get("TOTAL_CURRENT_LIABILITIES").toString();
				// 长期借款56
				String longtermLoan = fallMaps.get(i).get("LONGTERM_LOAN").toString();
				// 应付债券57
				String bondsPayable = fallMaps.get(i).get("BONDS_PAYABLE").toString();
				// 负债合计64
				String totalLiabilities = fallMaps.get(i).get("TOTAL_LIABILITIES").toString();
				// 实收资本66
				String paidIncapital = fallMaps.get(i).get("PAID_INCAPITAL").toString();
				// 实收资本66---上一年度
				String paidIncapitalLast = fallMaps.get(i - 1).get("PAID_INCAPITAL").toString();
				// 资本公积67
				String capitalSurplus = fallMaps.get(i).get("CAPITAL_SURPLUS").toString();
				// 资本公积67-----上一年度
				String capitalSurplusLast = fallMaps.get(i - 1).get("CAPITAL_SURPLUS").toString();
				// 盈余公积69
				String surplusReserve = fallMaps.get(i).get("SURPLUS_RESERVE").toString();
				// 未分配利润70
				String undistributedProfit = fallMaps.get(i).get("UNDISTRIBUTED_PROFIT").toString();
				// 所有者权益（或股东权益）合计71
				String totalOwnersEquity = fallMaps.get(i).get("TOTAL_OWNERS_EQUITY").toString();
				// 所有者权益（或股东权益）合计71----上一年度
				String totalOwnersEquityLast = fallMaps.get(i - 1).get("TOTAL_OWNERS_EQUITY").toString();
				// 负债和所有者权益总计73
				String totalLiabilitiesEquity = fallMaps.get(i).get("TOTAL_LIABILITIES_EQUITY").toString();
				// 主营业务收入77
				String mainBusinessIncome = fallMaps.get(i).get("MAIN_BUSINESS_INCOME").toString();
				// 主营业务收入77-----上一年度
				String mainBusinessIncomeLast = fallMaps.get(i - 1).get("MAIN_BUSINESS_INCOME").toString();
				// 主营业务成本78
				String mainBusinessCost = fallMaps.get(i).get("MAIN_BUSINESS_COST").toString();
				// 主营业务税金及附加79
				String mainOperationsTands = fallMaps.get(i).get("MAIN_OPERATIONS_TANDS").toString();
				// 营业费用82
				String operatingExpenses = fallMaps.get(i).get("OPERATING_EXPENSES").toString();
				// 管理费用83
				String managementExpenses = fallMaps.get(i).get("MANAGEMENT_EXPENSES").toString();
				// 财务费用84
				String financialExpenses = fallMaps.get(i).get("FINANCIAL_EXPENSES").toString();
				// 营业利润85
				String operatingProfit = fallMaps.get(i).get("OPERATING_PROFIT").toString();
				// 营业利润85-----上一年度
				String operatingProfitLast = fallMaps.get(i - 1).get("OPERATING_PROFIT").toString();
				// 投资收益86
				String incomeInvestment = fallMaps.get(i).get("INCOME_INVESTMENT").toString();
				// 补贴收入87
				String subsidyIncome = fallMaps.get(i).get("SUBSIDY_INCOME").toString();
				// 营业外收入88
				String nonoperatingIncome = fallMaps.get(i).get("NONOPERATING_INCOME").toString();
				// 利润总额90
				String totalProfit = fallMaps.get(i).get("TOTAL_PROFIT").toString();
				// 净利润92
				String netProfit = fallMaps.get(i).get("NET_PROFIT").toString();
				// 经营活动产生的现金流量净额114
				String operatingActivitiesNetamount = fallMaps.get(i).get("OPERATING_ACTIVITIES_NETAMOUNT").toString();
				// 年度
				String ownerYear = fallMaps.get(i).get("OWNER_YEAR").toString();

				DecimalFormat df = new DecimalFormat("0.00");
				/*
				 * 计算指标
				 */
				// 净资产收益率
				String onnetAssets = "";
				if (0 != ((Double.valueOf(totalOwnersEquityLast) + Double.valueOf(totalOwnersEquity)) / 2)) {
					onnetAssets = df.format(Double.valueOf(netProfit)
							/ ((Double.valueOf(totalOwnersEquityLast) + Double.valueOf(totalOwnersEquity)) / 2));
				}
				if (0 == ((Double.valueOf(totalOwnersEquityLast) + Double.valueOf(totalOwnersEquity)) / 2)) {
					onnetAssets = "0.00";
				}
				// 总资产报酬率
				String totalassetRewardrate = "";
				if ((Double.valueOf(totalAssetsLast) + Double.valueOf(totalAssets)) / 2 != 0) {
					totalassetRewardrate = df.format((Double.valueOf(totalProfit) + Double.valueOf(financialExpenses))
							/ ((Double.valueOf(totalAssetsLast) + Double.valueOf(totalAssets)) / 2));
				}
				if ((Double.valueOf(totalAssetsLast) + Double.valueOf(totalAssets)) / 2 == 0) {
					totalassetRewardrate = "0.00";
				}
				// 销售（应收）利润率
				String salesProfitMargin = "";
				if (0 != Double.valueOf(mainBusinessIncome)) {
					salesProfitMargin = df.format(Double.valueOf(totalProfit) / Double.valueOf(mainBusinessIncome));
				}
				if (0 == Double.valueOf(mainBusinessIncome)) {
					salesProfitMargin = "0.00";
				}
				// 盈余现金保障倍数
				String surplusGuaranteeMultiple = "";
				if (0 != Double.valueOf(netProfit)) {
					surplusGuaranteeMultiple = df
							.format(Double.valueOf(operatingActivitiesNetamount) / Double.valueOf(netProfit));
				}
				if (0 == Double.valueOf(netProfit)) {
					surplusGuaranteeMultiple = "0.00";
				}

				// 成本费用利润率（%）
				String costProfitMargin = "";
				if (0 != (Double.valueOf(mainBusinessCost) + Double.valueOf(mainOperationsTands)
						+ Double.valueOf(operatingExpenses) + Double.valueOf(managementExpenses)
						+ Double.valueOf(financialExpenses))) {
					costProfitMargin = df.format(Double.valueOf(totalProfit) / (Double.valueOf(mainBusinessCost)
							+ Double.valueOf(mainOperationsTands) + Double.valueOf(operatingExpenses)
							+ Double.valueOf(managementExpenses) + Double.valueOf(financialExpenses)));
				}
				if (0 == (Double.valueOf(mainBusinessCost) + Double.valueOf(mainOperationsTands)
						+ Double.valueOf(operatingExpenses) + Double.valueOf(managementExpenses)
						+ Double.valueOf(financialExpenses))) {
					costProfitMargin = "0.00";
				}
				// 资本收益率（%）
				String capitalYield = "";
				if (0 != ((Double.valueOf(paidIncapitalLast) + Double.valueOf(paidIncapital)
						+ Double.valueOf(capitalSurplusLast) + Double.valueOf(capitalSurplus)) / 2)) {
					capitalYield = df.format(Double.valueOf(netProfit)
							/ ((Double.valueOf(paidIncapitalLast) + Double.valueOf(paidIncapital)
									+ Double.valueOf(capitalSurplusLast) + Double.valueOf(capitalSurplus)) / 2));
				}
				if (0 == ((Double.valueOf(paidIncapitalLast) + Double.valueOf(paidIncapital)
						+ Double.valueOf(capitalSurplusLast) + Double.valueOf(capitalSurplus)) / 2)) {
					capitalYield = "0.00";
				}

				// 总资产周转率
				String turnoverTotalAssets = "";
				if (0 != ((Double.valueOf(totalAssetsLast) + Double.valueOf(totalAssets)) / 2)) {
					turnoverTotalAssets = df.format(Double.valueOf(mainBusinessIncome)
							/ ((Double.valueOf(totalAssetsLast) + Double.valueOf(totalAssets)) / 2));
				}
				if (0 == ((Double.valueOf(totalAssetsLast) + Double.valueOf(totalAssets)) / 2)) {
					turnoverTotalAssets = "0.00";
				}
				// 应收帐款周转率
				String accountsReceivableTurnover = "";
				if (0 != ((Double.valueOf(accountsReceivableLast) + Double.valueOf(accountsReceivable)) / 2)) {
					accountsReceivableTurnover = df.format(Double.valueOf(mainBusinessIncome)
							/ ((Double.valueOf(accountsReceivableLast) + Double.valueOf(accountsReceivable)) / 2));
				}
				if (0 == ((Double.valueOf(accountsReceivableLast) + Double.valueOf(accountsReceivable)) / 2)) {
					accountsReceivableTurnover = "0.00";
				}
				// 流动资产周转率
				String turnoverRateCurrentassets = "";
				if (0 != ((Double.valueOf(totalCurrentAssetsLast) + Double.valueOf(totalCurrentAssets)) / 2)) {
					turnoverRateCurrentassets = df.format(Double.valueOf(mainBusinessIncome)
							/ ((Double.valueOf(totalCurrentAssetsLast) + Double.valueOf(totalCurrentAssets)) / 2));
				}
				if (0 == ((Double.valueOf(totalCurrentAssetsLast) + Double.valueOf(totalCurrentAssets)) / 2)) {
					turnoverRateCurrentassets = "0.00";
				}
				// 资产现金回收率
				String cashRecoveryRate = "";
				if (0 != ((Double.valueOf(totalAssetsLast) + Double.valueOf(totalAssets)) / 2)) {
					cashRecoveryRate = df.format(Double.valueOf(operatingActivitiesNetamount)
							/ ((Double.valueOf(totalAssetsLast) + Double.valueOf(totalAssets)) / 2));
				}
				if (0 == ((Double.valueOf(totalAssetsLast) + Double.valueOf(totalAssets)) / 2)) {
					cashRecoveryRate = "0.00";
				}
				// 资产负债率
				String assetLiabilityRatio = "";
				if (0 != Double.valueOf(totalAssets)) {
					assetLiabilityRatio = df.format(Double.valueOf(totalLiabilities) / Double.valueOf(totalAssets));
				}
					if (0 == Double.valueOf(totalAssets)) {
						assetLiabilityRatio = "0.00";
					}
				
				// 已获利息倍数
				String interestCoverage = "";
				if (0 != Double.valueOf(financialExpenses)) {
					interestCoverage = df.format((Double.valueOf(totalProfit) + Double.valueOf(financialExpenses))
							/ Double.valueOf(financialExpenses));
				}
				if (0 == Double.valueOf(financialExpenses)) {
					interestCoverage = "0.00";
				}
				// 速动比率
				String quickRatio = "";
				if (0 != Double.valueOf(totalCurrentLiabilities)) {
					quickRatio = df.format((Double.valueOf(totalCurrentAssets) - Double.valueOf(stock))
							/ Double.valueOf(totalCurrentLiabilities));
				}
				if (0 == Double.valueOf(totalCurrentLiabilities)) {
					quickRatio = "0.00";
				}
				// 现金流动负债比率
				String cashflowLiabilityRatio = "";
				if (0 != Double.valueOf(totalCurrentAssets)) {
					cashflowLiabilityRatio = df
							.format(Double.valueOf(operatingActivitiesNetamount) / Double.valueOf(totalCurrentAssets));
				}
				if (0 == Double.valueOf(totalCurrentAssets)) {
					cashflowLiabilityRatio = "0.00";
				}
				// 带息负债比率
				String interestRateLiabilityRatio = "";
				if (0 != Double.valueOf(totalLiabilities)) {
					interestRateLiabilityRatio = df
							.format((Double.valueOf(shorttermLoan) + Double.valueOf(interestPayable)
									+ Double.valueOf(duenonCurrentLiabilities) + Double.valueOf(longtermLoan)
									+ Double.valueOf(bondsPayable)) / Double.valueOf(totalLiabilities));
				}
				if (0 == Double.valueOf(totalLiabilities)) {
					interestRateLiabilityRatio = "0.00";
				}
				// 销售（营收）增长率
				String salesGrowthRate = "";
				if (0 != Double.valueOf(mainBusinessIncomeLast)) {
					salesGrowthRate = df
							.format(Double.valueOf(mainBusinessIncome) / Double.valueOf(mainBusinessIncomeLast) - 1);
				}
				if (0 == Double.valueOf(mainBusinessIncomeLast)) {
					salesGrowthRate = "0.00";
				}
				// 资本保值增值率
				String rateCapitalAccumulation = "";
				if (0 != Double.valueOf(totalOwnersEquityLast)) {
					rateCapitalAccumulation = df
							.format(Double.valueOf(totalOwnersEquity) / Double.valueOf(totalOwnersEquityLast));
				}
				if (0 == Double.valueOf(totalOwnersEquityLast)) {
					rateCapitalAccumulation = "0.00";
				}
				// 销售（营收）利润增长率
				String salesProfitGrowthRate = "";
				if (0 != Double.valueOf(operatingProfitLast)) {
					salesProfitGrowthRate = df
							.format(1 - (Double.valueOf(operatingProfit) / Double.valueOf(operatingProfitLast)));
				}
				if (0 == Double.valueOf(operatingProfitLast)) {
					salesProfitGrowthRate = "0.00";
				}
				// 总资产增长率
				String totalAssetGrowthRate = "";
				if (0 != Double.valueOf(totalAssetsLast)) {
					totalAssetGrowthRate = df.format((Double.valueOf(totalAssets) - Double.valueOf(totalAssetsLast))
							/ Double.valueOf(totalAssetsLast));
				}
				if (0 == Double.valueOf(totalAssetsLast)) {
					totalAssetGrowthRate = "0.00";
				}
				// 存货周转率
				String inventoryTurnover = "";
				if (0 != ((Double.valueOf(stockLast) + Double.valueOf(stock)) / 2)) {
					inventoryTurnover = df.format(Double.valueOf(mainBusinessCost)
							/ ((Double.valueOf(stockLast) + Double.valueOf(stock)) / 2));
				}
				if (0 == ((Double.valueOf(stockLast) + Double.valueOf(stock)) / 2)) {
					inventoryTurnover = "0.00";
				}
				// 两金占流动资产比重
				String twogoldProportion = "";
				if (0 != Double.valueOf(totalCurrentAssets)) {
					twogoldProportion = df.format((Double.valueOf(accountsReceivable) + Double.valueOf(stock))
							/ Double.valueOf(totalCurrentAssets));
				}
				if (0 == Double.valueOf(totalCurrentAssets)) {
					twogoldProportion = "0.00";
				}
				// 成本费用占营业总收入比重
				String costaccountProportion = "";
				if (0 != (Double.valueOf(mainBusinessIncome) + Double.valueOf(incomeInvestment)
						+ Double.valueOf(subsidyIncome) + Double.valueOf(nonoperatingIncome))) {
					costaccountProportion = df.format((Double.valueOf(mainBusinessCost)
							+ Double.valueOf(mainOperationsTands) + Double.valueOf(operatingExpenses)
							+ Double.valueOf(managementExpenses) + Double.valueOf(financialExpenses))
							/ (Double.valueOf(mainBusinessIncome) + Double.valueOf(incomeInvestment)
									+ Double.valueOf(subsidyIncome) + Double.valueOf(nonoperatingIncome)));
				}
				if (0 == (Double.valueOf(mainBusinessIncome) + Double.valueOf(incomeInvestment)
						+ Double.valueOf(subsidyIncome) + Double.valueOf(nonoperatingIncome))) {
					costaccountProportion = "0.00";
				}
				// 资本积累率
				String capitalAccumulationRate = "";
				if (0 != Double.valueOf(totalOwnersEquityLast)) {
					capitalAccumulationRate = df
							.format(Double.valueOf(totalOwnersEquity) / Double.valueOf(totalOwnersEquityLast) - 1);
				}
				if (0 == Double.valueOf(totalOwnersEquityLast)) {
					capitalAccumulationRate = "0.00";
				}

				/*
				 * //流动比率 double currentRatio =
				 * Double.valueOf(totalCurrentAssets)/Double.valueOf(
				 * totalCurrentLiabilities); //现金比率 double cashRatio =
				 * Double.valueOf(monetaryFund)/Double.valueOf(
				 * totalCurrentLiabilities); //利息保障倍数 double
				 * interestGuaranteeTimes =
				 * (Double.valueOf(totalProfit)+Double.valueOf(financialExpenses
				 * ))/Double. valueOf(financialExpenses); //销售毛利率 double
				 * grossProfitMargin =
				 * (Double.valueOf(mainBusinessIncome)-Double.valueOf(
				 * mainBusinessCost))/Double. valueOf(mainBusinessIncome);
				 * //销售净利率 double netSellingRate =
				 * Double.valueOf(netProfit)/Double.valueOf(mainBusinessIncome);
				 * //资产净利率 double netassetInterestRate =
				 * Double.valueOf(netProfit)/((Double.valueOf(totalAssetsLast)+
				 * Double.valueOf( totalAssets))/2); //现金周转率 double cashTurnover
				 * = Double.valueOf(mainBusinessIncome)/((Double.valueOf(
				 * monetaryFundLast)+Double. valueOf(monetaryFund))/2); //存货周转天数
				 * double inventoryTurnoverDays =
				 * ((Double.valueOf(stockLast)+Double.valueOf(stock))/2)/Double.
				 * valueOf( mainBusinessCost)*365; //应收帐款周转天数 double
				 * turnoverdaysAccountsRb =
				 * ((Double.valueOf(accountsReceivableLast)+Double.valueOf(
				 * accountsReceivable))/
				 * 2)/Double.valueOf(mainBusinessIncome)*365;
				 */
				// 其他财务指标......
				// 运营资产
				String operatingAssets = df.format((Double.valueOf(totalCurrentAssets)
						- Double.valueOf(totalCurrentLiabilities) + Double.valueOf(totalOwnersEquity)) / 2);
				// 流动比率X1
				String currentRatioX1 = "";
				if (0 != Double.valueOf(totalCurrentLiabilities)) {
					currentRatioX1 = df
							.format(Double.valueOf(totalCurrentAssets) / Double.valueOf(totalCurrentLiabilities));
				}
				if (0 == Double.valueOf(totalCurrentLiabilities)) {
					currentRatioX1 = "0.00";
				}
				// 速动比率X2
				String quickRatioX2 = quickRatio;
				// X3
				String x3 = "";
				if (0 != Double.valueOf(totalOwnersEquity)) {
					x3 = df.format(Double.valueOf(totalCurrentLiabilities) / Double.valueOf(totalOwnersEquity));
				}
				if (0 == Double.valueOf(totalOwnersEquity)) {
					x3 = "0.00";
				}
				// X4
				String x4 = "";
				if (0 != Double.valueOf(totalOwnersEquity)) {
					x4 = df.format(Double.valueOf(totalLiabilities) / Double.valueOf(totalOwnersEquity));
				}
				if (0 == Double.valueOf(totalOwnersEquity)) {
					x4 = "0.00";
				}
				// 企业风险估值
				double riskValuation = 0;
				if (0 != Double.valueOf(totalCurrentLiabilities) && 0 != Double.valueOf(totalOwnersEquity)) {
					riskValuation = Double.valueOf(totalCurrentAssets) / Double.valueOf(totalCurrentLiabilities)
							+ (Double.valueOf(totalCurrentAssets) - Double.valueOf(stock))
									/ Double.valueOf(totalCurrentLiabilities)
							- Double.valueOf(totalCurrentLiabilities) / Double.valueOf(totalOwnersEquity)
							- Double.valueOf(totalLiabilities) / Double.valueOf(totalOwnersEquity);
				}
				if (0 == Double.valueOf(totalCurrentLiabilities) && 0 != Double.valueOf(totalOwnersEquity)) {
					riskValuation = 0.00;
				}
				// 企业评价结果
				String evaluationResult = "";
				// 赊销额度占营运资产的比例%
				double theProportion = 0.00;
				String theacaAssets = "";// 占比
				if (riskValuation <= -4.6) {
					evaluationResult = "高风险";
					theacaAssets = "0%";
				} else if (riskValuation >= -4.59 && riskValuation <= -3.2) {
					evaluationResult = "高风险";
					theProportion = 0.05;
					theacaAssets = "5%";
				} else if (riskValuation >= -3.19 && riskValuation <= -1.8) {
					evaluationResult = "高风险";
					theProportion = 0.1;
					theacaAssets = "10%";
				} else if (riskValuation >= -1.79 && riskValuation <= 0.4) {
					evaluationResult = "一般风险";
					theProportion = 0.15;
					theacaAssets = "15%";
				} else if (riskValuation >= -0.39 && riskValuation <= 1.0) {
					evaluationResult = "一般风险";
					theProportion = 0.2;
					theacaAssets = "20%";
				} else if (riskValuation > 1.0) {
					evaluationResult = "低风险";
					theProportion = 0.25;
					theacaAssets = "25%";
				}
				// 赊销额度
				double creditLimit = (Double.valueOf(totalCurrentAssets) - Double.valueOf(totalCurrentLiabilities)
						+ Double.valueOf(totalOwnersEquity)) * theProportion;
				// // Z计分
				String x1 = "";
				String x2 = "";
				String zx3 = "";
				String zx4 = "";
				String x5 = "";
				if (0 != Double.valueOf(totalAssets)) {
					x1 = df.format((Double.valueOf(totalCurrentAssets) - Double.valueOf(totalLiabilities))
							/ Double.valueOf(totalAssets) * 0.717);
					x2 = df.format((Double.valueOf(surplusReserve) + Double.valueOf(undistributedProfit))
							/ Double.valueOf(totalAssets) * 0.847);
					zx3 = df.format((Double.valueOf(financialExpenses) + Double.valueOf(totalProfit))
							/ Double.valueOf(totalAssets) * 3.107);
					x5 = df.format((Double.valueOf(mainBusinessIncome) / Double.valueOf(totalAssets)) * 0.998);
				}
				if (0 == Double.valueOf(totalAssets)) {
					x1 = "0.00";
					x2 = "0.00";
					zx3 = "0.00";
					x5 = "0.00";
				}
				if (0 != Double.valueOf(totalLiabilities)) {
					zx4 = df.format((Double.valueOf(totalOwnersEquity) / Double.valueOf(totalLiabilities)) * 0.42);
				}
				if (0 == Double.valueOf(totalLiabilities)) {
					zx4 = "0.00";
				}
				// 查询是否上市
				Map<String, Object> map = new HashMap<String, Object>();
				String shlx = "";
				String developmentResult = "";
				double developmentalValuation = 0.0;
				map.put("pgId", pgId);
				map.put("indexBM", "200419");
				// map = autoScoreMapper.getQnQData(map);
				if (map != null) {
					shlx = (String) map.get("DATA_VALUE");
				}
				if ("001".equals(shlx) || "".equals(shlx)) {
					if (0 != Double.valueOf(totalAssets) && 0 != Double.valueOf(totalLiabilities)) {
						developmentalValuation = (0.717
								* ((Double.valueOf(totalCurrentAssets) - Double.valueOf(totalLiabilities))
										/ Double.valueOf(totalAssets) * 0.717))
								+ (0.847 * ((Double.valueOf(surplusReserve) + Double.valueOf(undistributedProfit))
										/ Double.valueOf(totalAssets) * 0.847))
								+ (3.107 * ((Double.valueOf(financialExpenses) + Double.valueOf(totalProfit))
										/ Double.valueOf(totalAssets) * 3.107))
								+ (0.42 * ((Double.valueOf(totalOwnersEquity) / Double.valueOf(totalLiabilities))
										* 0.42))
								+ (0.998 * ((Double.valueOf(mainBusinessIncome) / Double.valueOf(totalAssets))
										* 0.998));
					}
					if (0 != Double.valueOf(totalAssets) && 0 != Double.valueOf(totalLiabilities)) {
						developmentalValuation = 0.0;
					}
					if (developmentalValuation < 1.21) {
						developmentResult = "高风险";
					} else if (developmentalValuation >= 1.21 && developmentalValuation <= 2.99) {
						developmentResult = "一般风险";
					} else if (developmentalValuation > 2.99) {
						developmentResult = "低风险";
					}
				} else {
					if (0 != Double.valueOf(totalAssets) && 0 != Double.valueOf(totalLiabilities)) {
						developmentalValuation = (1.2
								* ((Double.valueOf(totalCurrentAssets) - Double.valueOf(totalLiabilities))
										/ Double.valueOf(totalAssets) * 0.717))
								+ (1.4 * ((Double.valueOf(surplusReserve) + Double.valueOf(undistributedProfit))
										/ Double.valueOf(totalAssets) * 0.847))
								+ (3.3 * ((Double.valueOf(surplusReserve) + Double.valueOf(undistributedProfit))
										/ Double.valueOf(totalAssets) * 0.847))
								+ (0.6 * ((Double.valueOf(financialExpenses) + Double.valueOf(totalProfit))
										/ Double.valueOf(totalAssets) * 3.107))
								+ (0.999 * ((Double.valueOf(mainBusinessIncome) / Double.valueOf(totalAssets))
										* 0.998));
					}

					if (developmentalValuation < 1.81) {
						developmentResult = "高风险";
					} else if (developmentalValuation >= 1.81 && developmentalValuation <= 2.99) {
						developmentResult = "一般风险";
					} else if (developmentalValuation > 2.99) {
						developmentResult = "低风险";
					}
				}

				/*
				 * //企业发展性估值 double developmentalValuation = x1+x2+zx3+zx4+x5;
				 * //企业发展性评价结果 String developmentResult = ""; if
				 * (developmentalValuation<1.21) { developmentResult="高风险"; }
				 * else if (developmentalValuation >= 1.21 &&
				 * developmentalValuation <= 2.99) { developmentResult="一般风险"; }
				 * else if (developmentalValuation > 2.99) {
				 * developmentResult="低风险"; }
				 */

				FinanceModel financeModel = new FinanceModel();
				financeModel.setPgId(pgId);
				// 净资产收益率
				financeModel.setOnnetAssets(HandleData(onnetAssets));
				// 总资产报酬率
				financeModel.setTotalassetRewardrate(HandleData(totalassetRewardrate));
				// 销售（应收）利润率
				financeModel.setSalesProfitMargin(HandleData(salesProfitMargin));
				// 盈余现金保障倍数
				financeModel.setSurplusGuaranteeMultiple(HandleData(surplusGuaranteeMultiple));
				// 成本费用利润率（%）
				financeModel.setCostProfitMargin(HandleData(costProfitMargin));
				// 资本收益率（%）
				financeModel.setCapitalYield(HandleData(capitalYield));
				// 总资产周转率
				financeModel.setTurnoverTotalAssets(HandleData(turnoverTotalAssets));
				// 应收帐款周转率
				financeModel.setAccountsReceivableTurnover(HandleData(accountsReceivableTurnover));
				// 流动资产周转率
				financeModel.setTurnoverRateCurrentassets(HandleData(turnoverRateCurrentassets));
				// 资产现金回收率
				financeModel.setCashRecoveryRate(HandleData(cashRecoveryRate));
				// 资产负债率
				financeModel.setAssetLiabilityRatio(HandleData(assetLiabilityRatio));
				// 已获利息倍数
				financeModel.setInterestCoverage(HandleData(interestCoverage));
				// 速动比率
				financeModel.setQuickRatio(HandleData(quickRatio));
				// 现金流动负债比率
				financeModel.setCashflowLiabilityRatio(HandleData(cashflowLiabilityRatio));
				// 带息负债比率
				financeModel.setInterestRateLiabilityRatio(HandleData(interestRateLiabilityRatio));
				// 销售（营收）增长率
				financeModel.setSalesGrowthRate(HandleData(salesGrowthRate));
				// 资本保值增值率
				financeModel.setRateCapitalAccumulation(HandleData(rateCapitalAccumulation));
				// 销售（营收）利润增长率
				financeModel.setSalesProfitGrowthRate(HandleData(salesProfitGrowthRate));
				// 总资产增长率
				financeModel.setTotalAssetGrowthRate(HandleData(totalAssetGrowthRate));
				// 存货周转率
				financeModel.setInventoryTurnover(HandleData(inventoryTurnover));
				// 两金占流动资产比重
				financeModel.setTwogoldProportion(HandleData(twogoldProportion));
				// 成本费用占营业总收入比重
				financeModel.setCostaccountProportion(HandleData(costaccountProportion));
				// 资本积累率
				financeModel.setCapitalAccumulationRate(HandleData(capitalAccumulationRate));

				financeModel.setOperatingAssets(HandleData(operatingAssets));
				financeModel.setCurrentRatioX1(HandleData(currentRatioX1));
				financeModel.setQuickRatioX2(HandleData(quickRatioX2));
				financeModel.setX3(HandleData(x3));
				financeModel.setX4(HandleData(x4));
				financeModel.setRiskValuation(HandleData(String.valueOf(riskValuation)));
				financeModel.setEvaluationResult(evaluationResult);
				financeModel.setCreditLimit(HandleData(String.valueOf(creditLimit)));
				// Z计分
				financeModel.setX1(HandleData(String.valueOf(x1)));
				financeModel.setX2(HandleData(String.valueOf(x2)));
				financeModel.setZx3(HandleData(String.valueOf(zx3)));
				financeModel.setZx4(HandleData(String.valueOf(zx4)));
				financeModel.setX5(HandleData(String.valueOf(x5)));
				financeModel.setDevelopmentalValuation(HandleData(String.valueOf(developmentalValuation)));
				financeModel.setDevelopmentResult(developmentResult);
				financeModel.setOwnerYear(ownerYear);
				// 总资产、收入、成本、所有者权益
				financeModel.setTotalLiabilitiesEquity(totalLiabilitiesEquity);
				financeModel.setMainBusinessIncome(mainBusinessIncome);
				financeModel.setMainBusinessCost(mainBusinessCost);
				financeModel.setTotalOwnersEquity(totalOwnersEquity);

				financeModel.setTheacaAssets(theacaAssets);// 赊销占比

				if (totalAssets.equals("0") && totalLiabilitiesEquity.equals("0")) {
					// 年度为空处理
					indexDao.insertFinanceDataNull(financeModel);
				} else {
					
					try {
						indexDao.saveFinanceData(financeModel);
		            } catch (Exception e) {
		                System.out.println(e.getMessage());
		            }
					
				}

			}
		}
	}

	private String HandleData(Object onnetAssets) {
		if (String.valueOf(onnetAssets) == "Infinity" || String.valueOf(onnetAssets) == "NaN") {
			onnetAssets = "0";
		}
		return (String) onnetAssets;
	}

	@Override
	public List<ColumnAndCal> selectCalFormulaBycolName(String colNameEN) {

		return indexDao.selectCalFormulaBycolName(colNameEN);
	}

	@Override
	public void editStatusById(String id) {
		indexDao.editStatusById(id);
	}

	@Override
	public void updateStatusBymodelId(String status, String modelId) {
		Map<String, String> params = new HashMap<String, String>();

		params.put("status", status);
		params.put("modelId", modelId);
		indexDao.updateStatusBymodelId(params);

	}

	@Override
	public String selectDataBycolmunEN(String colmunEN, String pgId) {
		Map<String, String> params = new HashMap<String, String>();
		params.put("colmunEN", colmunEN);
		params.put("pgId", pgId);
		return indexDao.selectDataBycolmunEN(params);
	}

	@Override
	public List<LinkedHashMap<String, Object>> searchFinanceIndexData(String pgId) {
		return indexDao.searchFinanceIndexData(pgId);
	}

	@Override
	public String getTybmById(String userId) {
		return indexDao.getTybmById(userId);
	}

	@Override
	public void deleteIndexAndCatgoryById(List<String> list) {

		indexDao.deleteIndexAndCatgoryById(list);

	}

	@Override
	public List<Map<String, String>> selectModelBindIndex(String id, Page page) {

		return indexDao.selectModelBindIndexForPage(id, page);
	}

}
